#include "iap.h"
#include "iapsub.h"
//#include "app_flash.h"
//#include "ll_nb.h"

iapfun jump2app; 

   
void RxIntCallback_lp0(void) /* GPS module connected!*/
{


}

en_result_t  IAP_write_a_sertor(uint32_t startaddr,uint8_t *appbuf)
{
	uint32_t temp = 0;
	uint32_t fwaddr = startaddr;
	while(Ok != Flash_SectorErase(startaddr)); 
	for(int t = 0; t < 512; t += 4)
	{						    
		temp = (uint32_t)appbuf[3]<<24;
		temp += (uint32_t)appbuf[2]<<16;
		temp += (uint32_t)appbuf[1]<<8;
		temp += (uint32_t)appbuf[0];
		appbuf += 4;//偏移4字节 
		Flash_WriteWord(fwaddr+t,temp);		
	}
	return Ok;
}


//跳转到应用程序段
//appxaddr:用户代码起始地址
void iap_load_app(uint32_t appxaddr)
{
	if(((*(__IO uint32_t*)appxaddr)&0x2FFE0000)==0x20000000)	//检查栈顶地址是否合法
	{ 
		jump2app=(iapfun)*(__IO uint32_t*)(appxaddr+4);		//用户代码区的第二个字为程序开始地址（复位地址）		
		MSR_MSP(*(__IO uint32_t*)appxaddr);					//初始化APP堆栈指针（用户代码区的第一个字用于存放栈顶地址）
		jump2app();											//跳转到APP.
	}
}		 


#if 0

void IAP_start_check(void)
{
	en_result_t ret = Error;
	uint32_t option  = flash_read_one_word(flash_IAP_startaddr);
	printf("\r\nOption = %x",option);
        
#if 0 /*用于调试*/    
    for(int i = 0; i < 2048; i+=512 )
    {  
        ret = IAP_write_a_sertor(0x00003000+i,(uint8_t *)acbt_timer + i);
        if(ret == Ok)
        {
            printf("\r\nWrite flash [%x] successful",0x00003000+i);
        }	
    }
    printf("\r\n%08X",flash_read_one_word(0x3000));
    printf("\r\n%08X",flash_read_one_word(0x3004));
    printf("\r\n%08X",flash_read_one_word(0x3008));
 #endif
      
	if(option == FLASH_IAP_OPREAT_FLAG)
	{
		//执行升级操作
		nb_power_on();
		ll_nb_close_echo();
		delay1ms(500);
		/*注册到正式平台,平台会自动查询版本信息,此时平台会显示升级成功*/	
		//nb_putStr("AT+M2MCLISEND=00000131\r\n"); /*用于触发平台推送ota包 FOR TEST*/
  
		for(int i = 0; i < FLASH_APP_SIZE; i+=512 )
		{
			ll_nb_get_ota_pack(i);
			ret = IAP_write_a_sertor(FLASH_APP_ADDR+i,OTA.packbuffhex);
			if(ret == Ok)
			{
				printf("\r\nWrite flash [%x] successful",FLASH_APP_ADDR+i);
			}	
		}      
		printf("\r\nMCU OTA update successful!!!!");
		flash_modify_IAP_status(IAP_JUMP);
	}	
		printf("\r\nJump to App now!!!");	
		iap_load_app(FLASH_APP_ADDR);    ///*IAP 跳转*///  	
}

#nedif

/*****通过AT指令获取到app bin 文件****/

#endif

